package test;

import java.util.Collections;
import java.util.LinkedList;

public class Solution {
    int ptr;
    public String unzipString(String records) {
        LinkedList<String> stack = new LinkedList<>();
        ptr = 0;
        while (ptr < records.length()) {
            char cur = records.charAt(ptr);
            if (Character.isLetter(cur)) {
                String s = getLetters(records);
                stack.addLast(s);
            } else if (cur == '(' || cur == ')') {
                stack.addLast(String.valueOf(records.charAt(ptr++)));
            } else if (cur == '<') {
                int number = getNumber(records);
                LinkedList<String> sub = new LinkedList<>();
                while(!"(".equals(stack.peekLast())) {
                    if (stack.peekLast().equals(")") ){
                        stack.removeLast();
                        continue;
                    }
                    sub.addLast(stack.removeLast());
                }
                stack.removeLast();
                Collections.reverse(sub);
                StringBuilder t = new StringBuilder();
                String o = getString(sub);
                while (number-- > 0) {
                    t.append(o);
                }
                stack.addLast(t.toString());

            }
        }
        return getString(stack);
    }

    private int getNumber(String records) {
        StringBuilder s = new StringBuilder();
        while (Character.isDigit(records.charAt(++ptr))) {
            s.append(records.charAt(ptr));
        }
        ++ptr;
        return Integer.parseInt(s.toString());
    }

    public String getLetters(String s) {
        StringBuffer ret = new StringBuffer();
        while (ptr < s.length() && Character.isLetter(s.charAt(ptr))) {
            ret.append(s.charAt(ptr++));
        }
        return ret.toString();
    }

    public String getString(LinkedList<String> v) {
        StringBuffer ret = new StringBuffer();
        for (String s : v) {
            ret.append(s);
        }
        return ret.toString();
    }

    public static void main(String[] args) {
        System.out.println(new Solution().unzipString("abc(d)<2>e"));
    }



}
